package cn.bdqn.t354.dao;

import cn.bdqn.t354.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.List;

@SpringBootTest
@RunWith(SpringRunner.class)
public class UserDaoSpecificationTester {
    @Resource
    UserDao userDao;

    //4.specity动态查询
    @Test
    public void testFind(){
        //构造查询条件
        Specification<User> specification=new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                //1.获取查询的属性
                Path<Object> usrName = root.get("usrName");
                //2.构造查询条件
                Predicate dajun = cb.equal(usrName, "dajun");

                return dajun;
            }
        };

        List<User> list = userDao.findAll(specification);
        for (User user : list) {
            System.out.println(user);
        }

    }

    @Test
    public void testFind2(){
        //构造查询条件
        Specification<User> specification=new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                //1.获取查询的属性
                Path<Object> usrName = root.get("usrName");
                //2.构造查询条件
                Predicate dajun = cb.like(usrName.as(String.class), "%d%");

                return dajun;
            }
        };

        List<User> list = userDao.findAll(specification);
        for (User user : list) {
            System.out.println(user);
        }

    }

    @Test
    public void testFind3(){
        //构造查询条件
        Specification<User> specification=new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                //1.获取查询属性
                Path<Object> usrName = root.get("usrName");
                Path<Object> usrPassword = root.get("usrPassword");
                //2.构造查询条件
                Predicate p1 = cb.equal(usrName, "dajun");
                Predicate p2 = cb.equal(usrPassword, "123456");
                Predicate and = cb.and(p1, p2);

                return and;
            }
        };

        List<User> list = userDao.findAll(specification);
        for (User user : list) {
            System.out.println(user);
        }

    }

}
